#include "order/MultidatasAddtion.h"
#include <QSqlError>
#include "tools/Diary.h"
#include "tools/Pyscript.h"

MultidatasAddtion::MultidatasAddtion(QMap<ThreadPoint, NT::THREAD_STATE> &_pool_thread_,
                                     QMap<QString, QMap<QString, QString>> &_RGLRLMAP_,
                                     QMap<QString, QString> &_pool_chars_,
                                     QMap<QString, QList<QString>> &_pool_ststr_,
                                     QSqlDatabase *db){
    pool_thread = &_pool_thread_;
    pool_chars = &_pool_chars_;
    pool_ststr = &_pool_ststr_;
    RGLRLMAP = &_RGLRLMAP_;
    Query = QSqlQuery(*db);
    _RGLRLMAP_["REGEXP"]["HyperLinkExtract"].isEmpty() ? HyperLink = "http[s]?://.*" : HyperLink = _RGLRLMAP_["REGEXP"]["HyperLinkExtract"];
}


void MultidatasAddtion::run(){
    QMutex Lock;
    Lock.lock();
    QStringList mdrs_name_all = (*pool_ststr)["anysql-name"];
    QStringList mdrs_path_all = (*pool_ststr)["anysql-path"];
    QStringList mdrs_owner_all = (*pool_ststr)["anysql-owner"];
    QStringList mdrs_format_all = (*pool_ststr)["fm-ovall"];
    QStringList mdrs_format_image = (*pool_ststr)["fm-image"];
    QStringList mdrs_local_files = (*pool_ststr)["mdrs-local-files"];
    QStringList mdrs_local_folder = (*pool_ststr)["mdrs-local-folders"];
    QStringList mdrs_extrafd;
    diary5("fd - ", !mdrs_local_folder.isEmpty(), " fl - ", !mdrs_local_files.isEmpty(), " task start now", Diary::Debug)
    if (!mdrs_local_folder.isEmpty())
    {
        mdrs_extrafd.append(mdrs_local_folder);
        SCROPED_LOCAL_FIND(mdrs_local_folder, NULL, mdrs_format_all, MatchingMode_Simple, mdrs_local_files)
    }
    if (!mdrs_local_files.isEmpty())
    {
        mdrs_extrafd.append(definfc.canonicalPath(mdrs_local_files));
    }
    mdrs_extrafd.removeDuplicates();
    (*pool_ststr)["mdrs-local-files"].clear();
    (*pool_ststr)["mdrs-local-folders"].clear();
    QString mdrs_df_owner = (*pool_chars)["mdrs-owner"];
    int index = 0;
    while (index < mdrs_local_files.size())
    {
        if ((*pool_thread)[ThreadPoint::MULTI_ADDTION] == NT::THREAD_TERMINATED)
        {
            break;
        }
        else if ((*pool_thread)[ThreadPoint::MULTI_ADDTION] == NT::THREAD_PAUSE)
        {
            while (true)
            {
                if ((*pool_thread)[ThreadPoint::MULTI_ADDTION] == NT::THREAD_PAUSE)
                {
                    QThread::msleep(15);
                    continue;
                }
                else
                {
                    break;
                }
            }
        }
        else
        {
            QMap<QString, QString> mdrs_sql_info;
            PPScriptExec::PyScript_MediainfoGet("outer_script",
                                                                  "multi_mediaread",
                                                                  mdrs_local_files[index].toStdString().c_str(),
                                                                  mdrs_sql_info);
            QString mdrs_name = mdrs_sql_info["simple_name"];
            QString mdrs_path = mdrs_sql_info["read_path"];
            QString mdrs_suffix = mdrs_sql_info["file_suffix"];
            QString mdrs_artist = mdrs_sql_info["media_artist"];
            QString mdrs_prdtime = mdrs_sql_info["file_prddate"];
            QString mdrs_size = mdrs_sql_info["file_size"];
            QString mdrs_duration = mdrs_sql_info["file_duration"];
            QString mdrs_bitrate = mdrs_sql_info["file_bitrate"];
            QString mdrs_curtime = QDateTime().currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
            if (mdrs_name_all.contains(mdrs_name))
            {
                int mdrs_index = mdrs_name_all.indexOf(mdrs_name);
                QString mdrs_map_path = mdrs_path_all[mdrs_index];
                QString mdrs_map_owner = mdrs_owner_all[mdrs_index];
                QFileInfo mdrs_path_info(mdrs_map_path);
                if (!QRegularExpression(HyperLink).match(mdrs_map_path).capturedTexts().isEmpty())
                {
                    if (RdoMap_Bool[mdrs_map_path])
                    {
                        index++;
                        continue;
                    }
                    else
                    {
                        bool QueryStat = PPScriptExec::PyScript_AssertReply("outer_script",
                                                                                                        "verify_requests",
                                                                                                        mdrs_map_path.toStdString().c_str(),
                                                                                                        (*RGLRLMAP)["BKHD"]);
                        if (QueryStat)
                        {
                            RdoMap_Bool[mdrs_map_path] = QueryStat;
                            index++;
                            continue;
                        }
                        else
                        {
                            QString Sqlparser = "DELETE FROM media_datum WHERE mdrs_name='%1'";
                            Query.exec(Sqlparser.arg(mdrs_name));
                        }
                    }
                }

                else
                {
                   //如果该路径存在,并且目标为文件
                   if (mdrs_path_info.exists() &&
                       mdrs_map_owner.contains(mdrs_df_owner)){
                        QList<QString> mdrs_cols({"mdrs_artist", "mdrs_suffix", "mdrs_size", "mdrs_duration", "mdrs_bitrate",
                                                  "mdrs_state", "prd_time", "alter_time"});
                        QList<QString> mdrs_values({mdrs_artist, mdrs_suffix, mdrs_size, mdrs_duration, mdrs_bitrate, QString::number(false),
                                                    mdrs_prdtime, mdrs_curtime});
                        QList<QString> updates;
                        for(int how = 0;how < mdrs_cols.size(); how++) updates.append(mdrs_cols[how] + " = " + QString("'%1'").arg(mdrs_values[how]));
                        Query.exec(QString("UPDATE media_datum SET %1 WHERE mdrs_name='%2';").arg(updates.join(","), mdrs_name));

                   }
                   else
                   {
                        QStringList mdrs_owner = mdrs_map_owner.split("&&"); mdrs_owner.insert(0, mdrs_df_owner);
                        QString mdrs_owner_add = mdrs_owner.join("&&");
                        QList<QString> mdrs_cols({"mdrs_artist", "mdrs_path", "mdrs_suffix", "mdrs_size", "mdrs_duration", "mdrs_bitrate",
                                                  "prd_time", "alter_time", "owner"});
                        QList<QString> mdrs_values({mdrs_artist, mdrs_path, mdrs_suffix, mdrs_size, mdrs_duration, mdrs_bitrate,
                                                    mdrs_prdtime, mdrs_curtime, mdrs_owner_add});
                        QList<QString> updates;
                        for(int how = 0;how < mdrs_cols.size(); how++) updates.append(mdrs_cols[how] + " = " + QString("'%1'").arg(mdrs_values[how]));
                        Query.exec(QString("UPDATE media_datum SET %1, mdrs_state = %2 WHERE mdrs_name='%3';").arg(updates.join(","), QString::number(false), mdrs_name));
                   }
                }
            }
            else
            {
                if (!mdrs_size.isEmpty() &&
                    std::stod(mdrs_size.toStdString()))
                {
                    QString lyric = (*pool_chars)["mdrs_lyric"];
                    QList<QString> mdrs_col({"mdrs_name", "mdrs_artist", "mdrs_path", "mdrs_suffix", "mdrs_size", "mdrs_duration", "mdrs_bitrate",
                                             "mdrs_state", "prd_time", "alter_time", "mdrs_lyric", "owner"});
                    QList<QString> mdrs_values({mdrs_name, mdrs_artist, mdrs_path, mdrs_suffix, mdrs_size, mdrs_duration, mdrs_bitrate,
                                                QString::number(false), mdrs_prdtime, mdrs_curtime, lyric, mdrs_df_owner});
                    if ((*pool_ststr)["fm-ovall"].contains(mdrs_suffix))
                    {
                        Query.exec(QString("INSERT INTO media_datum(%1) values(%2);").arg(mdrs_col.join(","), definfc.join(mdrs_values, "'%1'", ",")));
                    }
                    else
                    {
                        index++;
                        continue;
                    }
                }
                else
                {
                    index++;
                    continue;
                }
            }
            emit process(((double)(index + 1) / mdrs_local_files.size()) * 100, mdrs_name);
            QThread::msleep(5);
        }
        index++;
    }
    Lock.unlock();
    if (!mdrs_local_files.isEmpty()) emit finish();
    (*pool_ststr)["mdrs-local-files"].clear();
    (*pool_thread)[ThreadPoint::MULTI_ADDTION] = NT::THREAD_IDLEABOUT;
}

